import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Space, Input, Form, Select, message, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getProductList, ProductInfo, ProductListParams } from '../../../services/product';
import './styles.css';

const { Option } = Select;

const ProductList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ProductInfo[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取产品列表数据
  const fetchProductList = async (params: ProductListParams = {}) => {
    try {
      setLoading(true);
      const { current = 1, size = 10, ...restParams } = params;
      const response = await getProductList({
        current,
        size,
        ...restParams,
      });
      setData(response.records);
      setPagination({
        current: response.current,
        pageSize: response.size,
        total: response.total,
      });
    } catch (error) {
      console.log('error', error);
      message.error('获取产品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载
  useEffect(() => {
    fetchProductList();
  }, []);

  // 表格列配置
  const columns: ColumnsType<ProductInfo> = [
    {
      title: '基础支撑平台',
      dataIndex: 'platform',
      key: 'platform',
      width: 150,
      render: () => '上海（SH）',

    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
      render: (text, record) => (
        <Space>
          {record.mainImage && (
            <img src={record.mainImage} alt={text} style={{ width: 40, height: 40, objectFit: 'cover', borderRadius: '4px' }} />
          )}
          {text}
        </Space>
      ),
    },
    {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      width: 120,
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          DATA_REPORT: '数据报告',
          API: 'API接口',
          MODEL: '模型服务',
        };
        return typeMap[type] || type;
      },
    },
    {
      title: '行业类别',
      dataIndex: 'industryCategory',
      key: 'industryCategory',
      width: 120,
      render: (category: string) => {
        const categoryMap: Record<string, string> = {
          TELECOM: '电信',
          FINANCE: '金融',
          INDUSTRIAL_MANUFACTURING: '工业制造',
        };
        return categoryMap[category] || category;
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: number | undefined) => price !== undefined ? `¥${price}` : '-',
    },
    {
      title: '服务商',
      dataIndex: 'serviceProvider',
      key: 'serviceProvider',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          ON_SHELF: { text: '已上架', color: 'success' },
          OFF_SHELF: { text: '已下架', color: 'default' },
          PENDING: { text: '待审核', color: 'processing' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      key: 'auditStatus',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          APPROVED: { text: '已通过', color: 'success' },
          REJECTED: { text: '已拒绝', color: 'error' },
          PENDING: { text: '待审核', color: 'processing' },
        };
        const { text, color } = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = async (values: any) => {
    try {
      await fetchProductList({
        ...values,
        current: 1,
        size: pagination.pageSize,
      });
    } catch (error) {
      console.error('搜索失败:', error);
    }
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchProductList({
      current: 1,
      size: pagination.pageSize,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    fetchProductList({
      current: pagination.current,
      size: pagination.pageSize,
      ...form.getFieldsValue(),
      ...filters,
    });
  };

  // 处理编辑
  const handleEdit = (record: ProductInfo) => {
    console.log('编辑产品:', record);
  };

  // 处理查看
  const handleView = (record: ProductInfo) => {
    console.log('查看产品:', record);
  };

  // 处理删除
  const handleDelete = (record: ProductInfo) => {
    console.log('删除产品:', record);
  };

  return (
    <div>
      <Card bordered={false}>
      <Form
        form={form}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 24 }}
      >
        <Form.Item name="productName" label="产品名称">
          <Input placeholder="请输入产品名称" allowClear />
        </Form.Item>
        <Form.Item name="productType" label="产品类型">
          <Select placeholder="请选择产品类型" allowClear style={{ width: 200 }}>
            <Option value="DATA_REPORT">数据报告</Option>
            <Option value="API">API接口</Option>
            <Option value="MODEL">模型服务</Option>
          </Select>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
            <Option value="ON_SHELF">已上架</Option>
            <Option value="OFF_SHELF">已下架</Option>
            <Option value="PENDING">待审核</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

     

      <Table<ProductInfo>
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </Card>
    </div>
  );
};

export default ProductList; 